package com.lagou.rabbitmq.handler;

import com.lagou.rabbitmq.constants.OrderConstants;
import com.lagou.rabbitmq.constants.RabbitConstants;
import com.lagou.rabbitmq.domain.Order;
import com.lagou.rabbitmq.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @className: OrderHandler
 * @auther: Jerry
 * @date: 2021/3/19 20:33
 * @desctiption: TODO
 * @version: 1.0
 */
@Component
public class OrderHandler {

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = RabbitConstants.ORDER_DLX_QUEUE, ackMode = "MANUAL")
    public void onMessage(Message message, Channel channel) throws IOException {
        System.out.println("OrderHandler.handler...");
        String s = new String(message.getBody());
        Order o = orderService.getById(Long.parseLong(s));
        if (o != null && OrderConstants.TOPAID.getCode().equals(o.getOrderState())) {
            Order order = new Order();
            order.setId(o.getId());
            order.setOrderState(OrderConstants.CANCEL.getCode());
            order.setGmtModified(new Date());
            orderService.updateById(order);
        }
        // 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
